package handler

import (
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"yim_server/common/response"
	"yim_server/utils"
	"yim_server/yim_auth/auth_api/internal/logic"
	"yim_server/yim_auth/auth_api/internal/svc"
	"yim_server/yim_auth/auth_api/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func authenticationHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.AuthenticationRequest
		if err := httpx.ParseHeaders(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewAuthenticationLogic(r.Context(), svcCtx)

		// 验证是否在白名单中
		if utils.IsListByRegex(svcCtx.Config.WhiteList, req.ValidPath) {
			logx.Infof("%s 在白名单中", req.ValidPath)
			response.Response(r, w, nil, nil)
			return
		}
		if req.Token == "" {
			err := errors.New("认证失败")
			response.Response(r, w, nil, err)
			return
		}
		fmt.Println(r.Header)
		resp, err := l.Authentication(&req)
		response.Response(r, w, resp, err)
	}
}
